import React, {useEffect, useState,useContext, useRef} from 'react'
import { Table, Button, Form, Input } from 'antd';
import PandaIcon from '../../../assets/icon/PandaSvg'
import axios from 'axios'
const EditableContext = React.createContext(null);

export default function Category() {
  const [category, setcategory] = useState([])
  useEffect(() => {
    axios.get('/userList/getNewsCategory').then(response => {
      const {data: {data}} = response
      setcategory(data)
    })
  }, [])
  function handleSaves(record) {
    console.log(record)
    setcategory(category.map(item => {
      if (item.id === record.id) {
        return {
          id: item.id,
          title: item.title,
          value: item.title
        }
      }
      return item 
    }))
  }

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
      key: 'id',
    },
    {
      title: '栏目名称',
      dataIndex: 'title',
      align: 'center',
      onCell: (record, index) => ({
        record,
        editable: true,
        dataIndex: 'title',
        title: '栏目名称',
        handleSave: handleSaves,
      })
    },
    {
      title: '操作',
      dataIndex: 'address',
      align: 'center',
      key: 'address',
      render(h) {
        return (
          <Button shape="circle" icon={<PandaIcon />} />
        )
      },
    },
  ];

  const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };
  
  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
      if (editing) {
        inputRef.current.focus();
      }
    }, [editing]);
  
    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    };
  
    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({ ...record, ...values });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };
  
    let childNode = children;
  
    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0,
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title} is required.`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24,
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }
  
    return <td {...restProps}>{childNode}</td>;
  };

  return (
    <Table 
      bordered
      dataSource={category} 
      columns={columns}
      rowKey={item => item.id} 
      components={{
        body: {
          row: EditableRow,
          cell: EditableCell,
        },
      }}
    />
  )
}
